﻿using System.Linq;
using static Modules.Project.ProjectConstants;

namespace Modules.Project;

public static class ProjectStatusCalculator
{
    /// <summary>
    /// 根据项目状态变更记录计算每月指定状态指定月份天数
    /// </summary>
    /// <param name="records"></param>
    /// <param name="status"></param>
    /// <param name="month"></param>
    /// <returns></returns>
    public static int CalculateDaysOfStatus(IEnumerable<ProjectStatusChangeRecord> records, 项目状态 status, int month)
    {
        var daysOfMonths = CalculateDaysOfStatus(records, status);
        if (daysOfMonths.ContainsKey(month))
            return daysOfMonths[month];
        return 0;
    }

    /// <summary>
    /// 根据项目状态变更记录计算每月指定状态天数
    /// </summary>
    /// <param name="records"></param>
    /// <param name="status"></param>
    /// <returns></returns>
    public static Dictionary<int, int> CalculateDaysOfStatus(IEnumerable<ProjectStatusChangeRecord> records, 项目状态 status)
    {
        var daysUnderConstruction = new Dictionary<int, int>();

        var groupedRecords = records.GroupBy(r => new { r.EffectiveDate.Year, r.EffectiveDate.Month });

        foreach (var group in groupedRecords)
        {
            int underConstructionDays = 0;
            bool underConstruction = false;
            DateTime previousDate = DateTime.MinValue;

            foreach (var record in group.OrderBy(r => r.EffectiveDate))
            {
                if (record.NewStatus == status)
                {
                    if (!underConstruction)
                    {
                        underConstruction = true;
                        previousDate = record.EffectiveDate;
                    }
                }
                else
                {
                    if (underConstruction)
                    {
                        underConstructionDays += (record.EffectiveDate - previousDate).Days;
                        underConstruction = false;
                    }
                }
            }

            if (underConstruction)
            {
                underConstructionDays += (DateTime.DaysInMonth(group.Key.Year, group.Key.Month) - previousDate.Day + 1);
            }

            daysUnderConstruction.Add(group.Key.Year * 100 + group.Key.Month, underConstructionDays);
        }

        return daysUnderConstruction;
    }

    /// <summary>
    /// 指定时间是否为指定状态
    /// </summary>
    /// <param name="records"></param>
    /// <param name="date"></param>
    /// <param name="status"></param>
    /// <returns></returns>
    public static bool IsDateStatus(IEnumerable<ProjectStatusChangeRecord> records, DateTime date, 项目状态 status)
    {
        var previous = records.Where(m => date.Subtract(m.EffectiveDate).TotalDays >= 0).OrderByDescending(m => m.EffectiveDate).FirstOrDefault();
        if (previous != null && previous.NewStatus == status)
            return true;
        return false;
    }
}
